package org.marsdonne.auth;

import org.marsdonne.archives.Client;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;

import java.util.LinkedHashMap;
import java.util.Map;

public class AuthUtils {

    private AuthUtils() {
    }

    public static User getCurrentUser() {
        String username;
        Map jwtClaims = null;

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof Jwt) {
            Jwt jwt = (Jwt) principal;
            username = jwt.getSubject();
            jwtClaims = jwt.getClaims();
        } else {
            username = (String) principal;
            jwtClaims = new LinkedHashMap();
        }

        Object USER_ID = jwtClaims.get(User.Constants.USER_ID);
        Object USER_NAME = jwtClaims.get(User.Constants.USER_NAME);
        Object USER_REAL_NAME = jwtClaims.get(User.Constants.USER_REAL_NAME);
        Object USER_ORG_ID = jwtClaims.get(User.Constants.USER_ORG_ID);
        Object USER_ORG_NAME = jwtClaims.get(User.Constants.USER_ORG_NAME);
        Object USER_ORG_LICENSE_CODE = jwtClaims.get(User.Constants.USER_ORG_LICENSE_CODE);

        User user = new User(
                USER_ID instanceof Long ? (Long) USER_ID : null,
                USER_NAME == null ? username : USER_NAME.toString(),
                USER_REAL_NAME == null ? null : USER_REAL_NAME.toString(),
                Client.valueOf(jwtClaims.get(User.Constants.USED_CLIENT).toString()),
                USER_ORG_ID instanceof Long ? (Long) USER_ORG_ID : null,
                USER_ORG_NAME == null ? null : USER_ORG_NAME.toString(),
                USER_ORG_LICENSE_CODE == null ? null : USER_ORG_LICENSE_CODE.toString()
        );

        return user;
    }

}
